package controllers

import (
	"egin/app/request"
	"egin/app/service"
	"egin/pkg/redigo"
	"egin/pkg/response"
	"egin/pkg/vali"
	"encoding/json"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
)

func PermissionRoleTree(c *gin.Context) {
	list := service.PermissionRoleTree()
	response.SuccessWithData(list, c)
}

//权限 管理页面
func PermissionIndexHtml(c *gin.Context) {
	c.HTML(http.StatusOK, "permission/index.tmpl", nil)
}

//PermissionCreateHtml 添加角色页面
func PermissionCreateHtml(c *gin.Context) {
	c.HTML(http.StatusOK, "permission/create.tmpl", nil)
}

//PermissionEditHtml 修改角色页面
func PermissionEditHtml(c *gin.Context) {
	permission, _ := service.GetPermission(c)
	permissionJson, err := json.Marshal(permission)
	if err != nil {
		zap.L().Error("PermissionEditHtml json err", zap.Error(err))
	}

	c.HTML(http.StatusOK, "permission/edit.tmpl", gin.H{"permission": string(permissionJson)})
}

//PermissionIndex  获取角色列表数据
func PermissionIndex(c *gin.Context) {

	list, err := service.GetPermissionList(c)
	if err == nil {
		response.SuccessWithData(list, c)
	} else {
		response.ErrorWithMessage("服务器错误", c)
	}
}

//PermissionCreate 添加角色
func PermissionCreate(c *gin.Context) {

	var param request.PermissionQs

	if err := c.ShouldBind(&param); err != nil {
		errStr := vali.ValidErrMsg(&param, err.(validator.ValidationErrors))
		response.ErrorWithMessage(errStr, c)
		return
	}

	err := service.PermissionAdd(param, c)
	if err == nil {
		response.SuccessWithMessage("添加成功", c)
	} else {
		response.ErrorWithMessage("添加失败", c)
	}
}

//PermissionEdit 修改角色
func PermissionEdit(c *gin.Context) {
	var param request.PermissionEditQs
	if err := c.ShouldBind(&param); err != nil {
		errStr := vali.ValidErrMsg(&param, err.(validator.ValidationErrors))
		response.ErrorWithMessage(errStr, c)
		return
	}

	err := service.PermissionEdit(param, c)
	if err == nil {
		conn := redigo.GetPool().Get()
		defer conn.Close()
		conn.Do("del", "admin_rbac")
		conn.Do("del", "admin_menu")
		response.SuccessWithMessage("修改成功", c)
	} else {
		response.ErrorWithMessage("修改失败", c)
	}
}

func PermissionDelete(c *gin.Context) {
	err := service.PermissionDelete(c)
	if err == nil {
		conn := redigo.GetPool().Get()
		defer conn.Close()
		conn.Do("del", "admin_rbac")
		conn.Do("del", "admin_menu")
		response.SuccessWithMessage("删除成功", c)
	} else {
		response.ErrorWithMessage("删除失败，该权限有被角色使用", c)
	}
}
